package com.example.libraryapp.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RadioButton;

import androidx.appcompat.widget.AppCompatRadioButton;

import com.example.libraryapp.R;
import com.example.libraryapp.util.DisplayUtil;

/**
 * @author 伍凯铭
 * @since 2020/8/3
 */
public class SmartRadioButton extends AppCompatRadioButton {

    private float mImgWidth;

    private float mImgHeight;

    public SmartRadioButton(Context context) {
        this(context, null);
    }

    public SmartRadioButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SmartRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setClickable(true);
        //init
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.SmartRadioButton);
        mImgWidth = array.getDimension(R.styleable.SmartRadioButton_rbWidth, DisplayUtil.dp2px(context,20));
        mImgHeight = array.getDimension(R.styleable.SmartRadioButton_rbHeight, DisplayUtil.dp2px(context,20));
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //让RadioButton的图标可调大小 属性：
        Drawable drawableLeft = this.getCompoundDrawables()[0];//获得文字左侧图片
        Drawable drawableTop = this.getCompoundDrawables()[1];//获得文字顶部图片
        Drawable drawableRight = this.getCompoundDrawables()[2];//获得文字右侧图片
        Drawable drawableBottom = this.getCompoundDrawables()[3];//获得文字底部图片
        if (drawableLeft != null) {
            drawableLeft.setBounds(0, 0, (int) mImgWidth, (int) mImgHeight);
            this.setCompoundDrawables(drawableLeft, null, null, null);
        }
        if (drawableRight != null) {
            drawableRight.setBounds(0, 0, (int) mImgWidth, (int) mImgHeight);
            this.setCompoundDrawables(null, null, drawableRight, null);
        }
        if (drawableTop != null) {
            drawableTop.setBounds(0, 0, (int) mImgWidth, (int) mImgHeight);
            this.setCompoundDrawables(null, drawableTop, null, null);
        }
        if (drawableBottom != null) {
            drawableBottom.setBounds(0, 0, (int) mImgWidth, (int) mImgHeight);
            this.setCompoundDrawables(null, null, null, drawableBottom);
        }
    }
}
